import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Tabs,
  Form,
  Table,
  Input,
  Modal,
  Button,
  message,
  DatePicker,
} from 'antd';
import DataSet from "@antv/data-set";
import {
  Chart,
  Geom,
  Axis,
  Tooltip,
  Legend,
} from "bizcharts";
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

@connect(({ riskDetection, loading }) => ({
  riskDetection,
  loading: loading.models.riskDetection,
}))
@Form.create()
export default class RiskDetection extends PureComponent {
  state = {
    paramList: {
      dateRange: [],
    },
    showEditDialog: false,
  };

  componentDidMount() {
    this.getRiskData();
    this.getRiskSet();
  }

  getRiskData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {
      endDate: '',
      startDate: '',
    }
    if (paramList.dateRange && paramList.dateRange[0]) {
      [postParam.startDate, postParam.endDate] = [
        paramList.dateRange[0].format('YYYY-MM-DD') + ' ' + '00:00:00',
        paramList.dateRange[1].format('YYYY-MM-DD') + ' ' + '23:59:59',
      ];
    } else {
      postParam.startDate = moment(Date.parse(new Date())).format('YYYY-MM-DD') + ' ' + '00:00:00';
      postParam.endDate = moment(Date.parse(new Date())).format('YYYY-MM-DD HH:mm:ss');
    }
    console.log(postParam)
    dispatch({
      type: 'riskDetection/fetchGetUserPassRate',
      payload: {
        ...postParam
      }
    });
  };

  getRiskSet = () => {
    const { dispatch } = this.props;
    let postParam = {}
    dispatch({
      type: 'riskDetection/fetchGetPassRateConf',
      payload: {
        ...postParam
      }
    });
  };

  postUpdateRisk = (row) => {
    const { dispatch } = this.props;
    let postParam = {
      newPassRate: row.newPassRate,
      oldPassRate: row.oldPassRate,
      noChannelPassRate: row.noChannelPassRate,
    }
    console.log(postParam)
    dispatch({
      type: 'riskDetection/fetchUpdatePassRateConf',
      payload: {
        ...postParam
      },
      callback: (res) => {
        if (res.code == 200) {
          message.success(`${res.message}`);
        } else {
          message.error(`${res.message}`);
        }
      }
    }).then(() => {
      this.getRiskSet();
    })
  };

  onDateChange = (dates, dateString) => {
    const { paramList } = this.state;
    paramList.dateRange = dates;
    this.getRiskData();
  };

  formatRiskData = (srcData) => {
    let formatData = [];
    if (moment(srcData[srcData.length - 1].date, "YYYY-MM-DD HH:mm:ss").valueOf() - moment(srcData[0].date, "YYYY-MM-DD HH:mm:ss").valueOf() < 1000 * 60 * 60 *24) {
      srcData.forEach((val, index, arr) => {
        let _buf = {
          time: val.date.substring(11, val.date.length - 3),
          '新客通过': val.newPassRate,
          '老客通过': val.oldPassRate,
        }
        formatData.push(_buf);
      });
    } else {
      srcData.forEach((val, index, arr) => {
        let _buf = {
          time: val.date,
          '新客通过': val.newPassRate,
          '老客通过': val.oldPassRate,
        }
        formatData.push(_buf);
      });
    }
    return formatData
  };

  handleShowEdit = () => {
    this.setState({
      showEditDialog: true
    })
  };

  handleEditOk = () => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue, ccc) => {
      if (!err) {
        this.postUpdateRisk(fieldsValue);
        this.setState({
          showEditDialog: false
        });
      }
    })
  };

  handleEditCancel = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      showEditDialog: false
    })
  };

  render() {
    const { riskDetection: { getUserPassRateData, getPassRateConfData }, loading, form } = this.props;
    const { getFieldDecorator } = form;
    
    const tableColumns = [{
        title: '日期',
        dataIndex: 'date',
        key: 'date',
        render: val => `${val}`
    }, {
        title: '新客预警率',
        dataIndex: 'demo1',
        key: 'demo1',
        render: val => '25%'
    }, {
        title: '新客通过率',
        dataIndex: 'newPassRate',
        key: 'newPassRate',
        render: val => `${val}%`
    }, {
        title: '老客预警率',
        dataIndex: 'demo3',
        key: 'demo3',
        render: val => '80%'
    }, {
        title: '老客通过率',
        dataIndex: 'oldPassRate',
        key: 'oldPassRate',
        render: val => `${val}%`
    }];

    const __trendData = getUserPassRateData && getUserPassRateData.length > 0 ? this.formatRiskData(getUserPassRateData) : [],
    _xFields = ['新客通过', '老客通过'];

    const ds = new DataSet();
    const dv = ds.createView().source(__trendData);
    dv.transform({
      type: "fold",
      fields: _xFields,
      // 展开字段集
      key: "range",
      // key字段
      value: "_rate" // value字段
    });
    const cols = {
      time: {
        range: [0, 1]
      }
    };

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    return (
      <PageHeaderLayout title="风控检测">
        <Card bordered={false}>
          <div style={{marginBottom: 20}}>
            <RangePicker
              placeholder={[moment(Date.parse(new Date())).format('YYYY-MM-DD') + ' ' + '0点', '当前时间']}
              onChange={this.onDateChange}
            />
            <div style={{float: 'right'}}><Button type="primary" onClick={() => {this.handleShowEdit()}}>设置</Button></div>
          </div>

          <div style={{marginBottom: 20}}>
            <Chart height={400} data={dv} scale={cols} forceFit>
              <Legend />
              <Axis name="time" />
              <Axis name="_rate" label={{ formatter: val => `${val}%` }} />
              <Tooltip crosshairs={{ type: "y" }} itemTpl="<tr><td style=&quot;width:70px&quot;>{name}:</td><td>{value}%</td></tr>" />
              <Geom type="line" position="time*_rate" size={2} color={"range"} />
              <Geom type="point" position="time*_rate" size={4} shape={"circle"} color={"range"} style={{ stroke: "#fff", lineWidth: 1 }} />
            </Chart>
          </div>

          <Table
            loading={loading}
            dataSource={getUserPassRateData}
            columns={tableColumns}
            rowKey={record => record['date']}
          />
        </Card>

        <Modal
          title="设置阈值"
          visible={this.state.showEditDialog}
          onOk={this.handleEditOk}
          onCancel={this.handleEditCancel}
        >
          <Form layout={'horizontal'}>
            <div>
              <FormItem label="新客通过率%" {...formItemLayout}>
                {getFieldDecorator('newPassRate', {
                  rules: [{ required: true, pattern: /^[0-9]*$/, message: '请输入正确的通过率' }],
                  initialValue: getPassRateConfData.newPassRate,
                })(<Input />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="老客通过率%" {...formItemLayout}>
                {getFieldDecorator('oldPassRate', {
                  rules: [{ required: true, pattern: /^[0-9]*$/, message: '请输入正确的通过率' }],
                  initialValue: getPassRateConfData.oldPassRate,
                })(<Input />)}
              </FormItem>
            </div>
            <div>
              <FormItem label="无渠道通过率%" {...formItemLayout}>
                {getFieldDecorator('noChannelPassRate', {
                  rules: [{ required: true, pattern: /^[0-9]*$/, message: '请输入正确的通过率' }],
                  initialValue: getPassRateConfData.noChannelPassRate,
                })(<Input />)}
              </FormItem>
            </div>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
